package com.yint.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合节点
 * <p>
 * Created by 殷田 on 2018/5/3.
 */
public abstract class Composite extends Leaf {

    private List<Leaf> subs = new ArrayList<Leaf>();

    public final void addSub(Leaf sub) {
        if (sub != null && !subs.contains(sub)) {
            subs.add(sub);
        }
    }

    public final void removeSub(Leaf sub) {
        if (sub != null && subs.contains(sub)) {
            subs.remove(sub);
        }
    }

    protected final List<Leaf> getSubs() {
        return subs;
    }

    @Override
    protected boolean onEntry(Tree tree) {
        List<Leaf> subs = getSubs();
        if (subs == null || subs.size() == 0) {
            return false;
        }
        return true;
    }

    @Override
    protected void onLeave(Tree tree, STATUS state) {
        List<Leaf> subs = getSubs();
        if (subs != null && subs.size() > 0) {
            for (Leaf sub : subs) {
                sub.leave(tree);
            }
        }
    }
}
